<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI聊天测试页面</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        
        .header {
            text-align: center;
            color: #333;
            margin-bottom: 30px;
        }
        
        .status-panel {
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .chat-container {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .input-group {
            margin-bottom: 15px;
        }
        
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #555;
        }
        
        input[type="text"], textarea, select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            box-sizing: border-box;
        }
        
        textarea {
            height: 100px;
            resize: vertical;
        }
        
        button {
            background-color: #007bff;
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin-right: 10px;
            margin-bottom: 10px;
        }
        
        button:hover {
            background-color: #0056b3;
        }
        
        button:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
        
        .status-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 8px;
        }
        
        .status-online {
            background-color: #28a745;
        }
        
        .status-offline {
            background-color: #dc3545;
        }
        
        .response-area {
            margin-top: 20px;
            padding: 15px;
            background-color: #f8f9fa;
            border-radius: 4px;
            min-height: 100px;
            white-space: pre-wrap;
            border-left: 4px solid #007bff;
        }
        
        .error {
            color: #dc3545;
            background-color: #f8d7da;
            border-left-color: #dc3545;
        }
        
        .loading {
            color: #856404;
            background-color: #fff3cd;
            border-left-color: #ffc107;
        }
        
        .quick-buttons {
            margin: 15px 0;
        }
        
        .quick-btn {
            background-color: #6c757d;
            font-size: 14px;
            padding: 8px 16px;
        }
        
        .quick-btn:hover {
            background-color: #545b62;
        }
        
        .config-section {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
            margin-bottom: 20px;
        }
        
        @media (max-width: 600px) {
            .config-section {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>🤖 AI聊天测试页面</h1>
        <p>腾讯混元AI集成测试</p>
    </div>
    
    <div class="status-panel">
        <h3>服务状态</h3>
        <p>
            <span id="statusIndicator" class="status-indicator status-offline"></span>
            <span id="statusText">检查中...</span>
        </p>
        <button onclick="checkStatus()">检查状态</button>
        <button onclick="testConnection()">测试连接</button>
    </div>
    
    <div class="chat-container">
        <h3>AI聊天测试</h3>
        
        <div class="input-group">
            <label for="token">JWT Token:</label>
            <input type="text" id="token" placeholder="请输入您的JWT token" />
        </div>
        
        <div class="config-section">
            <div class="input-group">
                <label for="temperature">温度 (0.0-2.0):</label>
                <input type="number" id="temperature" value="0.7" min="0" max="2" step="0.1" />
            </div>
            <div class="input-group">
                <label for="maxTokens">最大Token数:</label>
                <input type="number" id="maxTokens" value="500" min="1" max="2048" />
            </div>
        </div>
        
        <div class="input-group">
            <label for="systemRole">系统角色 (可选):</label>
            <input type="text" id="systemRole" placeholder="例如：你是一个专业的编程助手" />
        </div>
        
        <div class="input-group">
            <label for="message">消息内容:</label>
            <textarea id="message" placeholder="请输入您想问的问题..."></textarea>
        </div>
        
        <div class="quick-buttons">
            <button class="quick-btn" onclick="setQuickMessage('你好，请介绍一下自己')">自我介绍</button>
            <button class="quick-btn" onclick="setQuickMessage('什么是Spring Boot？')">技术问题</button>
            <button class="quick-btn" onclick="setQuickMessage('写一个Java单例模式的代码示例')">代码示例</button>
            <button class="quick-btn" onclick="setQuickMessage('分析一下当前AI技术的发展趋势')">趋势分析</button>
        </div>
        
        <button id="sendBtn" onclick="sendMessage()">发送消息</button>
        <button onclick="quickChat()">快速聊天</button>
        <button onclick="clearResponse()">清空回复</button>
        
        <div id="response" class="response-area">
            AI回复将显示在这里...
        </div>
    </div>

    <script>
        const API_BASE = 'http://localhost:8083/api';
        
        // 检查服务状态
        async function checkStatus() {
            try {
                const token = document.getElementById('token').value;
                if (!token) {
                    alert('请先输入JWT token');
                    return;
                }
                
                const response = await fetch(`${API_BASE}/ai/status`, {
                    headers: { 'Authorization': `Bearer ${token}` }
                });
                
                const result = await response.json();
                const indicator = document.getElementById('statusIndicator');
                const text = document.getElementById('statusText');
                
                if (result.code === 200 && result.data) {
                    indicator.className = 'status-indicator status-online';
                    text.textContent = 'AI服务可用';
                } else {
                    indicator.className = 'status-indicator status-offline';
                    text.textContent = result.message || 'AI服务不可用';
                }
            } catch (error) {
                document.getElementById('statusIndicator').className = 'status-indicator status-offline';
                document.getElementById('statusText').textContent = '检查失败: ' + error.message;
            }
        }
        
        // 测试连接
        async function testConnection() {
            try {
                const token = document.getElementById('token').value;
                if (!token) {
                    alert('请先输入JWT token');
                    return;
                }
                
                showLoading('正在测试连接...');
                
                const response = await fetch(`${API_BASE}/ai/test`, {
                    headers: { 'Authorization': `Bearer ${token}` }
                });
                
                const result = await response.json();
                
                if (result.code === 200 && result.data) {
                    showResponse('✅ 连接测试成功！AI服务工作正常。');
                } else {
                    showError('❌ 连接测试失败: ' + (result.message || '未知错误'));
                }
            } catch (error) {
                showError('❌ 连接测试异常: ' + error.message);
            }
        }
        
        // 发送消息
        async function sendMessage() {
            const token = document.getElementById('token').value;
            const message = document.getElementById('message').value.trim();
            
            if (!token) {
                alert('请先输入JWT token');
                return;
            }
            
            if (!message) {
                alert('请输入消息内容');
                return;
            }
            
            try {
                showLoading('AI正在思考中...');
                document.getElementById('sendBtn').disabled = true;
                
                const requestData = {
                    message: message,
                    temperature: parseFloat(document.getElementById('temperature').value),
                    maxTokens: parseInt(document.getElementById('maxTokens').value)
                };
                
                const systemRole = document.getElementById('systemRole').value.trim();
                if (systemRole) {
                    requestData.systemRole = systemRole;
                }
                
                const response = await fetch(`${API_BASE}/ai/chat`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify(requestData)
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    showResponse(`🤖 AI回复:\n\n${result.data.content}\n\n📊 统计信息:\n- 响应时间: ${new Date(result.data.timestamp).toLocaleString()}\n- 会话ID: ${result.data.sessionId || '无'}`);
                } else {
                    showError('❌ 请求失败: ' + (result.message || '未知错误'));
                }
            } catch (error) {
                showError('❌ 请求异常: ' + error.message);
            } finally {
                document.getElementById('sendBtn').disabled = false;
            }
        }
        
        // 快速聊天
        async function quickChat() {
            const token = document.getElementById('token').value;
            const message = document.getElementById('message').value.trim();
            
            if (!token) {
                alert('请先输入JWT token');
                return;
            }
            
            if (!message) {
                alert('请输入消息内容');
                return;
            }
            
            try {
                showLoading('AI正在快速回复中...');
                
                const response = await fetch(`${API_BASE}/ai/quick-chat?message=${encodeURIComponent(message)}`, {
                    method: 'POST',
                    headers: { 'Authorization': `Bearer ${token}` }
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    showResponse(`🚀 快速回复:\n\n${result.data}`);
                } else {
                    showError('❌ 快速聊天失败: ' + (result.message || '未知错误'));
                }
            } catch (error) {
                showError('❌ 快速聊天异常: ' + error.message);
            }
        }
        
        // 设置快速消息
        function setQuickMessage(msg) {
            document.getElementById('message').value = msg;
        }
        
        // 显示响应
        function showResponse(text) {
            const responseDiv = document.getElementById('response');
            responseDiv.textContent = text;
            responseDiv.className = 'response-area';
        }
        
        // 显示错误
        function showError(text) {
            const responseDiv = document.getElementById('response');
            responseDiv.textContent = text;
            responseDiv.className = 'response-area error';
        }
        
        // 显示加载状态
        function showLoading(text) {
            const responseDiv = document.getElementById('response');
            responseDiv.textContent = text;
            responseDiv.className = 'response-area loading';
        }
        
        // 清空回复
        function clearResponse() {
            document.getElementById('response').textContent = 'AI回复将显示在这里...';
            document.getElementById('response').className = 'response-area';
        }
        
        // 页面加载完成后自动检查状态
        window.onload = function() {
            // 尝试从localStorage获取token
            const savedToken = localStorage.getItem('jwt_token');
            if (savedToken) {
                document.getElementById('token').value = savedToken;
            }
            
            // 监听token输入变化，自动保存
            document.getElementById('token').addEventListener('input', function() {
                localStorage.setItem('jwt_token', this.value);
            });
        };
    </script>
</body>
</html>
